package com.clubupc.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.clubupc.modelo.BaseBean;
import com.clubupc.negocio.MaterialNegocio;

@Controller
public class MaterialController {

	@RequestMapping(value = "/mant-material", method = RequestMethod.GET)
	protected ModelAndView mantMaterial(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView("material-mant");
	}

	@RequestMapping(value = "/creacionmaterial", method = RequestMethod.GET)
	protected ModelAndView creacionmaterial(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("material-mant");
		return mav;
	}

	@RequestMapping(value = "/crearmaterial", method = RequestMethod.POST)
	protected ModelAndView creamaterial(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("material-mant");
		String errores = "";

		String nombres = request.getParameter("nombres");
		String descripcion = request.getParameter("descripcion");
		MaterialNegocio ln = new MaterialNegocio();

		BaseBean material = ln.getMaterialByNom(nombres);

		if (material != null) {
			errores += "El material ya esta registrado";
		}

		if (errores.length() > 0) {
			mav.addObject("nombre", nombres);
			mav.addObject("descripcion", descripcion);
			mav.addObject("msjAlert", "Error+" + errores);
		} else {
			material = ln.createMaterial(nombres, descripcion);
			if (material.get("idMaterial") == null) {
				mav.addObject("msjAlert", "Error+Error desconocido al crear Material+comuniquese con el administrador");
			} else {
				mav = new ModelAndView("material-mant");
				mav.addObject("msjAlert", "Felicitaciones+Material creado con exito");
			}
		}
		return mav;
	}

}
